using System;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using System.Threading.Tasks;


#if UNITY_EDITOR
using UnityEditor;

public class WorkshopMaker : MonoBehaviour
{
    [SerializeField, Header("地图模型都放到MapRoot下")] private GameObject mapRoot;
    [SerializeField, Header("文件模型都放到Body3D下")] private GameObject fileRoot;
    [SerializeField, Header("这个不用管，用于生成预览图时只显示地图")] private GameObject hideRoot;

    public string ModPath
    {
        get => modPath;
        set => modPath = value;
    }
    private string modPath = "";

    public string ModExportPath
    {
        get => modExportPath;
        set => modExportPath = value;
    }
    private string modExportPath;

    public async Task GenerateModConfig()
    {
        if (mapRoot == null)
        {
            Debug.LogError("mapRoot未设置！");
            return;
        }

        var mapData = new WorkshopModData();
        // 生成地图数据
        foreach (Transform child in mapRoot.transform)
        {
            var modelName = child.name;
            WSMapData wsMapData = new WSMapData
            {
                modelName = $"{modelName}.fbx",
                transform = new TransformData(child)
            };
            mapData.mapDataList.Add(wsMapData);
        }
        // 生成文件数据
        foreach (Transform child in fileRoot.transform)
        {
            var nameArr = child.name.Split('_');
            if (nameArr.Length != 2)
            {
                Debug.LogError($"文件名格式错误: {child.name} Body3D下模型名字：QQ_lnk  对应的模型源文件名字：QQ_lnk.fbx");
                continue;
            }
            var checkName = nameArr[0];
            var checkExt = nameArr[1];
            var modelName = child.name;
            WSFileData wsFileData = new WSFileData
            {
                checkName = $"{checkName}.{checkExt}",
                modelName = $"{modelName}.fbx",
                transform = new TransformData(child)
            };
            mapData.fileDataList.Add(wsFileData);
        }
        await Task.Delay(1);
        // 保存配置
        var json = JsonUtility.ToJson(mapData, true);
        var path = Path.Combine(modPath, $"{nameof(WorkshopModData)}.json");
        await Task.Delay(1);
        File.WriteAllText(path, json);
        await Task.Delay(1);
        AssetDatabase.Refresh();
        Debug.Log($"配置保存成功: {path}");
    }

    public async Task GeneratePreviewImage()
    {
        if (mapRoot == null)
        {
            Debug.LogError("mapRoot未设置！");
            return;
        }

        var screenshotPath = Path.Combine(modPath, CommonDefine.PreviewImageName);

        hideRoot.SetActive(false);
        await Task.Delay(1);
        CaptureScreenshot(screenshotPath);
        await Task.Delay(1);
        Camera.main.targetTexture = null;
        hideRoot.SetActive(true);

        Debug.Log($"预览图已保存: {screenshotPath}");
    }

    public void ChooseMod()
    {
        string folderPath = EditorUtility.OpenFolderPanel("选择Mod资源路径", "Assets", "");
        if (!string.IsNullOrEmpty(folderPath))
        {
            ModPath = folderPath;
            EditorUtility.SetDirty(this);
        }
    }

    public void ChooseModExport()
    {
        string folderPath = EditorUtility.OpenFolderPanel("选择Mod导出路径", "", "");
        if (!string.IsNullOrEmpty(folderPath))
        {
            ModExportPath = folderPath;
            EditorUtility.SetDirty(this);
        }
    }

    public async void StartExport()
    {
        await GenerateModConfig();
        await GeneratePreviewImage();
        // 把ModPath文件夹拷贝一份到 ModExportPath下，且把文件夹里面.meta文件删掉
        await CopyModFolderAndCleanMeta();
    }

    private async Task CopyModFolderAndCleanMeta()
    {
        if (string.IsNullOrEmpty(modPath) || string.IsNullOrEmpty(modExportPath))
        {
            Debug.LogError("ModPath或ModExportPath未设置！");
            return;
        }
        if (!Directory.Exists(modPath))
        {
            Debug.LogError($"源文件夹不存在: {modPath}");
            return;
        }

        // 获取源文件夹名称
        string sourceFolderName = Path.GetFileName(modPath);
        string destinationPath = Path.Combine(modExportPath, sourceFolderName);      
        // 如果目标文件夹已存在，先删除
        if (Directory.Exists(destinationPath))
        {
            Directory.Delete(destinationPath, true);
            await Task.Delay(1);
        }

        // 使用FileUtil.CopyFileOrDirectory（Unity Editor专用API）
        FileUtil.CopyFileOrDirectory(modPath, destinationPath);
        await Task.Delay(1);
        // 删除所有.meta文件（使用Directory.GetFiles的递归搜索）
        string[] metaFiles = Directory.GetFiles(destinationPath, "*.meta", SearchOption.AllDirectories);
        foreach (string metaFile in metaFiles)
        {
            File.Delete(metaFile);
        }
        await Task.Delay(1);
        Debug.Log($"Mod文件夹导出成功: {destinationPath}");
    }

    public void CaptureScreenshot(string screenshotPath)
    {
        RenderTexture renderTexture = new RenderTexture(1920, 1080, 24);
        Camera.main.targetTexture = renderTexture;
        Camera.main.Render();

        RenderTexture.active = renderTexture;
        Texture2D screenshot = new Texture2D(1920, 1080, TextureFormat.RGB24, false);
        screenshot.ReadPixels(new Rect(0, 0, 1920, 1080), 0, 0);
        screenshot.Apply();

        byte[] data = screenshot.EncodeToPNG();
        File.WriteAllBytes(screenshotPath, data);
    }
}

[CustomEditor(typeof(WorkshopMaker))]
public class WorkshopMakerEditor : Editor
{
    public override void OnInspectorGUI()
    {
        DrawDefaultInspector();
        EditorGUILayout.Space();
        WorkshopMaker workshopMaker = (WorkshopMaker)target;

        // 选择'Mod路径'
        EditorGUILayout.Space(20);
        EditorGUILayout.LabelField("Mod资源路径", workshopMaker.ModPath);
        if (GUILayout.Button("选择Mod资源路径"))
        {
            workshopMaker.ChooseMod();
        }

        // 选择'Mod导出路径'
        EditorGUILayout.Space(20);
        EditorGUILayout.LabelField("Mod导出路径", workshopMaker.ModExportPath);
        if (GUILayout.Button("选择Mod导出路径"))
        {
            workshopMaker.ChooseModExport();
        }

        EditorGUILayout.Space(20);
        if (GUILayout.Button("开始导出", GUILayout.Height(50)))
        {
            workshopMaker.StartExport();
        }
    }
}
#endif

#region 数据结构

public class CommonDefine
{
    public const string PreviewImageName = "PreviewImage.png";
}

[Serializable]
public class WorkshopModData
{
    public List<WSMapData> mapDataList = new();
    public List<WSFileData> fileDataList = new();

    public WSFileData GetWSFileData(string fileName)
    {
        foreach (var fileData in fileDataList)
        {
            if (fileData.checkName == fileName)
            {
                return fileData;
            }
        }
        return null;
    }
}

[Serializable]
public class WSMapData
{
    public string modelName;
    public TransformData transform;
}

[Serializable]
public class WSFileData : WSMapData
{
    public string checkName;
}

[Serializable]
public struct TransformData
{
    public V3Data localPosition;
    public V3Data localEuler;
    public V3Data localScale;

    public TransformData(V3Data localPosition, V3Data localEuler, V3Data localScale)
    {
        this.localPosition = localPosition;
        this.localEuler = localEuler;
        this.localScale = localScale;
    }

    public TransformData(Transform transform) : this(new V3Data(transform.localPosition), new V3Data(transform.localEulerAngles), new V3Data(transform.localScale))
    {

    }

    public void ToTransform(Transform trans)
    {
        trans.localPosition = localPosition.ToVector3;
        trans.localEulerAngles = localEuler.ToVector3;
        trans.localScale = localScale.ToVector3;
    }
}

[Serializable]
public struct V3Data
{
    public float x;
    public float y;
    public float z;

    public Vector3 ToVector3 => new Vector3(x, y, z);

    public V3Data(float x, float y, float z)
    {
        this.x = x;
        this.y = y;
        this.z = z;
    }

    public V3Data(Vector3 vector3) : this(vector3.x, vector3.y, vector3.z)
    {

    }
}
#endregion